In this article, we are going to dynamically create links in list using JavaScript.

For example, we have an ol element with three li elements. See the following example.

<ol>
  <li>Home</li>
  <li>About</li>
  <li>Contact</li>
</ol>

Now we want to create links inside the li element. The result will be like the following example.

<ol>
  <li><a href="#home">Home</a></li>
  <li><a href="#about">About</a></li>
  <li><a href="#contact">Contact</a></li>
</ol>

To do that dynamically, first we have to select all li elements and then loop through them. However, first look at the example below.

Example : create links in li element. #
<ol>
  <li>Home</li>
  <li>About</li>
  <li>Contact</li>
</ol>
<script>
const lists = document.querySelectorAll("ol li");
for(let i = 0; i<lists.length; i++) {
  let text = lists[i].innerText;
  lists[i].innerText = "";
  let newA = document.createElement("a");
  newA.href = "#"+text;
  newA.innerText = text;
  lists[i].appendChild(newA);
}
</script>
Try it Yourself »
  1. In the above example, we have an ol element with three li elements.
    <ol>
      <li>Home</li>
      <li>About</li>
      <li>Contact</li>
    </ol>
  2. We have selected all li elements using the querySelectorAll() method and stored in a variable as a nodeList.
    const lists = document.querySelectorAll("ol li");
  3. Inside the for loop, we have selected the current li element's text in a variable and set the li element's value to empty.
    for(let i = 0; i<lists.length; i++) {
      let text = lists[i].innerText;
      lists[i].innerText = "";
    }
  4. Then, we have created anchor element using the createElement() method and set its href to the current li element's value plus # sign. Also, set the anchor element's value as the li (current) element's value is.
    let newA = document.createElement("a");
      newA.href = "#"+text;
      newA.innerText = text;
  5. Now, it's time to append the created anchor element to the current li element.
    lists[i].appendChild(newA);